package com.simple.space.util.excel;

import com.simple.space.util.TimeUtil;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class ExcelExportUtil {
	// 导出文件类型Csv
	public static final String DOC_TYPE_CSV = "csv";
	// 导出文件类型Excel
	public static final String DOC_TYPE_EXCEL = "xls";

	public static final String FORMAT_DIR = "yyyyMMdd";
	public static final String FORMAT_FILENAME = "_yyyyMMdd_HHmmss";
	
	public static void excelExport(HttpServletRequest request,
			HttpServletResponse response, String fileName, String[] hearders,
			String[] fields, List dataList) {
		/*String path = request.getSession().getServletContext()
				.getRealPath("download");*/
		String path = "D:\\";

		Calendar cd = Calendar.getInstance();

		String fileDateName = String.valueOf(cd.get(Calendar.YEAR))
				+ String.valueOf(cd.get(Calendar.MONTH) + 1)
				+ String.valueOf(cd.get(Calendar.DATE));

		File file = new File(path + "\\" + fileDateName + "\\");

		if (!file.exists())
			file.mkdirs();

		String curTime = TimeUtil.dateToString(new Date());
		curTime = "_"
				+ curTime.replaceAll("-", "").replaceAll(":", "")
						.replaceAll(" ", "_");

		String newFileName = fileName + curTime + ".xls";

		String filePath = path + "\\" + fileDateName + "\\" + newFileName;

		// 1、创建创建导出对象
		ExportExcel e = new ExportExcel();
		e.setHeaders(getHeaders(fields, hearders, new Integer[0]));

		OutputStream fos = null;
		try {
			fos = new FileOutputStream(new File(filePath));
			// 导出数据
			e.export(fos, dataList, "UTF-8");
		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		export(request, response, filePath, newFileName);
	}
	
	public static void excelExport(HttpServletRequest request,
			HttpServletResponse response, String fileName,
			List<String[]> heardersList, List<String[]> fieldsList,
			List dataList, List<String> sheetNameList) {
		String path = request.getSession().getServletContext()
				.getRealPath("download");

		Calendar cd = Calendar.getInstance();

		String fileDateName = String.valueOf(cd.get(Calendar.YEAR))
				+ String.valueOf(cd.get(Calendar.MONTH) + 1)
				+ String.valueOf(cd.get(Calendar.DATE));

		File file = new File(path + "\\" + fileDateName + "\\");

		if (!file.exists())
			file.mkdirs();

		String curTime = TimeUtil.dateToString(new Date());
		curTime = "_"
				+ curTime.replaceAll("-", "").replaceAll(":", "")
						.replaceAll(" ", "_");

		String newFileName = fileName + curTime + ".xls";

		String filePath = path + "\\" + fileDateName + "\\" + newFileName;

		// 1、创建创建导出对象
		ExportExcel e = new ExportExcel();

//		e.setHeaders(getHeaders(fields, hearders, new Integer[0]));

		OutputStream fos = null;
		try {
			fos = new FileOutputStream(new File(filePath));
			// 导出数据
			e.export(fos, dataList, "UTF-8", fieldsList, heardersList, sheetNameList);
		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		export(request, response, filePath, newFileName);
	}
	
	public static void excelExport(HttpServletRequest request,
			HttpServletResponse response, String fileName, String[] hearders,
			String[] fields, List dataList, Integer[] columnWidths) {
		String path = request.getSession().getServletContext()
				.getRealPath("download");

		Calendar cd = Calendar.getInstance();

		String fileDateName = String.valueOf(cd.get(Calendar.YEAR))
				+ String.valueOf(cd.get(Calendar.MONTH) + 1)
				+ String.valueOf(cd.get(Calendar.DATE));

		File file = new File(path + "\\" + fileDateName + "\\");

		if (!file.exists())
			file.mkdirs();

		String curTime = TimeUtil.dateToString(new Date());
		curTime = "_"
				+ curTime.replaceAll("-", "").replaceAll(":", "")
						.replaceAll(" ", "_");

		String newFileName = fileName + curTime + ".xls";

		String filePath = path + "\\" + fileDateName + "\\" + newFileName;

		// 1、创建创建导出对象
		ExportExcel e = new ExportExcel();

		e.setHeaders(getHeaders(fields, hearders, columnWidths));

		OutputStream fos = null;
		try {
			fos = new FileOutputStream(new File(filePath));
			// 导出数据
			e.export(fos, dataList, "UTF-8");
		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		export(request, response, filePath, newFileName);
	}

	public static void export(HttpServletRequest request,
			HttpServletResponse response, String downloadfile, String fileName) {
		OutputStream o = null;
		java.io.FileInputStream in = null;
		try {
			o = response.getOutputStream();
			byte b[] = new byte[500];
			File fileLoad = new File(downloadfile);

			response.reset();

			response.setContentType("application/csv");

			String userAgent = request.getHeader("USER-AGENT");
			String newFilename = "";
			if (StringUtils.contains(userAgent, "Edge")) { // Edge
				newFilename = java.net.URLEncoder.encode(fileName, "UTF-8");
				;
			} else if (StringUtils.contains(userAgent, "Chrome")
					|| StringUtils.contains(userAgent, "Firefox")) { // google,火狐浏览器
				newFilename = new String(fileName.getBytes("utf-8"),
						"ISO_8859_1");
			} else {
				newFilename = java.net.URLEncoder.encode(fileName, "UTF-8"); // 其他浏览器
			}

			response.setHeader("content-disposition", "attachment; filename="
					+ newFilename);
			long fileLength = fileLoad.length();
			String len = String.valueOf(fileLength);
			response.setHeader("Content_Length", len);
			in = new java.io.FileInputStream(fileLoad);
			int n;
			while ((n = in.read(b)) != -1) {
				o.write(b, 0, n);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
					in = null;
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}

			if (o != null) {
				try {
					o.close();
					o = null;
				} catch (IOException e2) {
					e2.printStackTrace();
				}
			}
		}
	}

	/**
	 * 创建列头
	 * 
	 * @return
	 */
	public static List<ExcelColumn> getHeaders(String[] fields,
			String[] hearders, Integer[] widths) {
		List<ExcelColumn> columnList = null;
		if (hearders != null && fields != null && widths != null
				&& hearders.length == fields.length) {
			int len = hearders.length;
			int widthLen = widths.length;
			columnList = new ArrayList<ExcelColumn>(len);
			int width = 100;
			for (int i = 0; i < len; i++) {
				ExcelColumn ec = new ExcelColumn();
				ec.setFieldName(fields[i]);
				ec.setName(hearders[i]);
				if (widthLen > i) {
					width = widths[i];
				}
				ec.setWidth(width);
				columnList.add(ec);
			}
		}
		return columnList;
	}
	
	/**
	 * fileName 文件名称 
	 * hearders  列名1@field1@列名2@field2@列名3@field3
	 * list  List<Map<String,Object>
	 * 
	 * @param request
	 * @param response
	 * @param fileName 
	 * @param hearders
	 * @param list
	 *//*
	public static void export(HttpServletRequest request, HttpServletResponse response, String fileName, String hearders, List<Map<String,String>> list,String docType) {
		String dirs = request.getSession().getServletContext().getRealPath("download") + File.separator + format(ExcelExportUtil.FORMAT_DIR);
		String formatFileName = fileName+format(ExcelExportUtil.FORMAT_FILENAME);
		String filePath = dirs + File.separatorChar + formatFileName;
		
		File file = new File(dirs);		
		if(!file.exists())file.mkdirs();
		if(DOC_TYPE_CSV.equals(docType)){
			filePath += "." + DOC_TYPE_CSV;
			formatFileName += "." + DOC_TYPE_CSV;
			boolean isSuccess = exportCsvServer(filePath , hearders, list, DOC_TYPE_CSV);	
			if (isSuccess)  exportClient(response, filePath, formatFileName, DOC_TYPE_CSV);
		}
		if(DOC_TYPE_EXCEL.equals(docType)){
			filePath += "." + DOC_TYPE_EXCEL;
			formatFileName += "." + DOC_TYPE_EXCEL;
			boolean isSuccess = exportExcelServer(filePath, fileName, hearders, list, DOC_TYPE_EXCEL);	
			if (isSuccess)  exportClient(response, filePath, formatFileName, DOC_TYPE_EXCEL);
		}

	}*/
	
	/**
	 * 将服务器文件传到客户端
	 * *//*
	public static void exportClient(HttpServletResponse response, String filePath, String fileName, String docType) {
		OutputStream os = null;
		FileInputStream is = null;
		try {
			File file = new File(filePath);
			os = response.getOutputStream();
			is = new FileInputStream(file);
			byte b[] = new byte[500];
	 
			response.reset();	
			response.setContentType("application/" + docType);
			response.setHeader("content-disposition", "attachment; filename=" + new String(fileName.getBytes("GB2312"), "ISO_8859_1"));
			response.setHeader("Content_Length", String.valueOf(file.length()));
			int n;
			while ((n = is.read(b)) != -1) {
				os.write(b, 0, n);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
					is = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
			if (os != null) {
				try {
					os.close();
					os = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}*/
	
	/**
	 * 将list写到服务器文件中
	 * *//*
	public static boolean exportCsvServer(String filePath, String hearders, List<Map<String,String>> list, String docType) {
		boolean isSucess = false;

		FileOutputStream out = null;
		OutputStreamWriter osw = null;
		BufferedWriter bw = null;
		try {
			out = new FileOutputStream(new File(filePath));
			osw = new OutputStreamWriter(out);
			bw = new BufferedWriter(osw);				
				
			StringBuffer sbHearder = new StringBuffer();
			String[] arr = hearders.split("@");
			String[] arrField  = new String[arr.length/2] ;
			for(int i=0;i<arr.length;i++) {
				if(i%2 == 0){
					sbHearder.append(arr[i]);
					if( i != (arr.length -2)){
						sbHearder.append(",");
					}
					if( i == (arr.length -2)){
						sbHearder.append("\r");
					}
				}
				if(i%2 == 1){
					arrField[(i-1)/2] = arr[i];
				}					
			}
			bw.append(sbHearder.toString());
	
			if (isEmptyList(list)) {
				for (Map<String,String> map: list){
					StringBuffer sbData = new StringBuffer();
					for(int i=0 ; i < arrField.length ; i++){
						String str = map.get(arrField[i]) == null ? "" : (String)map.get(arrField[i]);
						sbData.append(str);
						if(i != (arrField.length - 1)){
							sbData.append(",");
						}
						if(i == (arrField.length - 1)){
							sbData.append("\r");
						}
					}
					bw.append(sbData.toString());
				}				
			}
			isSucess = true;
		} catch (Exception e) {
			isSucess = false;
		} finally {
			if (bw != null) {
				try {
					bw.close();
					bw = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (osw != null) {
				try {
					osw.close();
					osw = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (out != null) {
				try {
					out.close();
					out = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return isSucess;
	}
	
	
	*//**
	 * 将list写到服务器文件中
	 * *//*
	public static boolean exportExcelServer(String filePath, String sheetName, String hearders, List<Map<String,String>> list, String docType) {
		boolean isSucess = false;
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(new File(filePath));
			HSSFWorkbook wb = new HSSFWorkbook();
			HSSFSheet sheet = wb.createSheet(sheetName);			

			String[] arr = hearders.split("@");
			String[] arrField  = new String[arr.length/2] ;
			HSSFRow cellHR = sheet.createRow(0);
			for(int i=0;i<arr.length;i++) {
				if(i%2 == 0){
					HSSFCell cellH = cellHR.createCell(i/2);
					cellH.setCellValue(arr[i]);
				}
				if(i%2 == 1){
					arrField[(i-1)/2] = arr[i];
				}					
			}
	
			if (isEmptyList(list)) {
				for (int j=0 ; j < list.size() ; j++){
					Map<String,String>  map = list.get(j);
					HSSFRow cellSR = sheet.createRow(j+1);
					for(int i=0 ; i < arrField.length ; i++){
						HSSFCell cellS = cellSR.createCell(i);
						cellS.setCellValue((String)map.get(arrField[i]));
					}
				}				
			}
			wb.write(out);
			isSucess = true;
		} catch (Exception e) {
			isSucess = false;
		} finally {
			if (out != null) {
				try {
					out.close();
					out = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return isSucess;
	}*/
	/**
	 * 工具方法
	 * *//*
	
	public  static String format(String str){
		SimpleDateFormat sdf = new SimpleDateFormat(str);
		return sdf.format(new Date());
	}*/
	
	/*public static boolean isEmptyList(List  list){
		return list == null ? false : (list.size() == 0 ? false :true);
	}
	
	public static boolean isEmptyString(String str){
		return str == null ? false : (str.length() == 0 ? false :true) ;
	}*/
}
